﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using WCS.Entities;
using WCS.Entities.Api;

namespace WCS.Filters
{
    public class ExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 异常过滤
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            _logger.LogError($"调用{context.ActionDescriptor.DisplayName}出现未处理异常\n{context.Exception}");

            context.Result = new JsonResult(ApiResultHelp.Error("服务器出现未处理异常"));
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
